<template>
  <view class="order-page">
    
    <!-- 状态筛选 -->
    <scroll-view scroll-x class="status-scroll">
      <view 
        v-for="(item, index) in statusList" 
        :key="index"
        :class="['status-item', activeStatus === index ? 'active' : '']"
        @click="changeStatus(index)"
      >
        {{item}}
      </view>
    </scroll-view>
    
    <!-- 订单列表 -->
    <scroll-view 
      scroll-y 
      class="order-list"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore"
    >
      <!-- 订单卡片 -->
      <view 
        v-for="(order, index) in orderList" 
        :key="index"
        class="order-card"
        @click="viewDetail(order.id)"
      >
        <view class="order-header">
          <text class="order-no">订单编号: {{order.orderNo}}</text>
          <text class="order-status" :style="{color: getStatusColor(order.status)}">{{order.statusText}}</text>
        </view>
        
        <view class="goods-info">
          <image :src="order.goodsImage" class="goods-image"></image>
          <view class="goods-detail">
            <text class="goods-title">{{order.goodsTitle}}</text>
            <text class="goods-spec">{{order.spec}}</text>
            <text class="goods-price">¥{{order.price}}</text>
          </view>
        </view>
        
        <view class="order-footer">
          <text class="order-time">{{order.createTime}}</text>
          <text class="order-amount">共{{order.quantity}}件 合计: ¥{{order.totalAmount}}</text>
        </view>
        
        <view class="order-actions">
          <button 
            v-if="order.status === 1" 
            class="action-btn cancel-btn"
            @click.stop="cancelOrder(order.id)"
          >取消订单</button>
          <button 
            v-if="order.status === 2" 
            class="action-btn pay-btn"
            @click.stop="goToPay(order.id)"
          >立即支付</button>
          <button 
            v-if="order.status === 3" 
            class="action-btn confirm-btn"
            @click.stop="confirmReceipt(order.id)"
          >确认收货</button>
          <button 
            v-if="[4,5].includes(order.status)" 
            class="action-btn view-btn"
            @click.stop="viewDetail(order.id)"
          >查看详情</button>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more">
        <text v-if="loading">加载中...</text>
        <text v-else-if="noMore">没有更多订单了</text>
      </view>
      
      <!-- 空状态 -->
      <view v-if="orderList.length === 0 && !loading" class="empty-order">
        <image src="/static/images/empty-order.png" class="empty-image"></image>
        <text class="empty-text">暂无订单</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>

export default {
  data() {
    return {
      statusList: ['全部', '待付款', '待发货', '待收货', '已完成', '已取消'],
      activeStatus: 0,
      orderList: [],
      page: 1,
      pageSize: 10,
      loading: false,
      noMore: false,
      refreshing: false
    }
  },
  onLoad() {
    this.loadOrders()
  },
  methods: {
    // 加载订单
    async loadOrders() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        // 实际项目中调用API获取订单
        // const res = await uni.request({
        //   url: '/api/secondhand/orders',
        //   data: {
        //     status: this.activeStatus === 0 ? null : this.activeStatus,
        //     page: this.page,
        //     pageSize: this.pageSize
        //   }
        // })
        
        // 模拟数据
        setTimeout(() => {
          const newOrders = this.generateMockOrders(this.page)
          
          if (this.page === 1) {
            this.orderList = newOrders
          } else {
            this.orderList = [...this.orderList, ...newOrders]
          }
          
          this.loading = false
          this.refreshing = false
          this.noMore = newOrders.length < this.pageSize
        }, 800)
      } catch (err) {
        console.error('获取订单失败', err)
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
        this.loading = false
        this.refreshing = false
      }
    },
    
    // 生成模拟订单数据
    generateMockOrders(page) {
      const statusMap = [
        {status: 1, text: '待付款', color: '#ff4d4f'},
        {status: 2, text: '待发货', color: '#ff9f43'},
        {status: 3, text: '待收货', color: '#2e86de'},
        {status: 4, text: '已完成', color: '#10ac84'},
        {status: 5, text: '已取消', color: '#999'}
      ]
      
      const goodsList = [
        {
          title: '九成新iPhone 13 Pro',
          image: 'https://pic1.zhimg.com/80/v2-6afa72220d29f045a4b1b9f8a2b9c1b9_720w.webp',
          price: 4999
        },
        {
          title: 'MacBook Pro 2021',
          image: 'https://pic1.zhimg.com/80/v2-3b4b6e7b8c1d1e0e8e0e8e0e8e0e8e0e_720w.webp',
          price: 8999
        },
        {
          title: '索尼WH-1000XM4耳机',
          image: 'https://pic1.zhimg.com/80/v2-6afa72220d29f045a4b1b9f8a2b9c1b9_720w.webp',
          price: 1299
        },
        {
          title: 'Kindle Paperwhite',
          image: 'https://pic1.zhimg.com/80/v2-3b4b6e7b8c1d1e0e8e0e8e0e8e0e8e0e_720w.webp',
          price: 699
        }
      ]
      
      return Array(5).fill().map((_, i) => {
        const goods = goodsList[Math.floor(Math.random() * goodsList.length)]
        const status = statusMap[Math.floor(Math.random() * statusMap.length)]
        const orderNo = `SH${Date.now()}${page}${i}`
        
        return {
          id: page * 100 + i,
          orderNo,
          goodsTitle: goods.title,
          goodsImage: goods.image,
          spec: '默认规格',
          price: goods.price,
          quantity: Math.floor(Math.random() * 2) + 1,
          totalAmount: goods.price * (Math.floor(Math.random() * 2) + 1),
          status: status.status,
          statusText: status.text,
          createTime: this.formatTime(Date.now() - Math.floor(Math.random() * 86400000 * 7))
        }
      })
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    
    // 获取状态颜色
    getStatusColor(status) {
      const colors = {
        1: '#ff4d4f', // 待付款
        2: '#ff9f43', // 待发货
        3: '#2e86de', // 待收货
        4: '#10ac84', // 已完成
        5: '#999'     // 已取消
      }
      return colors[status] || '#333'
    },
    
    // 改变状态筛选
    changeStatus(index) {
      this.activeStatus = index
      this.page = 1
      this.noMore = false
      this.loadOrders()
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.page = 1
      this.loadOrders()
    },
    
    // 加载更多
    loadMore() {
      if (this.noMore || this.loading) return
      this.page++
      this.loadOrders()
    },
    
    // 查看详情
    viewDetail(id) {
      uni.navigateTo({
        url: `/pages/mine/orderDetail/orderDetail?id=${id}`
      })
    },
    
    // 取消订单
    cancelOrder(id) {
      uni.showModal({
        title: '提示',
        content: '确定要取消该订单吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '处理中...'
            })
            
            // 实际项目中调用API取消订单
            setTimeout(() => {
              uni.hideLoading()
              uni.showToast({
                title: '订单已取消',
                icon: 'success'
              })
              this.onRefresh()
            }, 800)
          }
        }
      })
    },
    
    // 去支付
    goToPay(id) {
      uni.navigateTo({
        url: `/pages/secondhand/payment?id=${id}`
      })
    },
    
    // 确认收货
    confirmReceipt(id) {
      uni.showModal({
        title: '提示',
        content: '请确认已收到商品，确认后将完成交易',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '处理中...'
            })
            
            // 实际项目中调用API确认收货
            setTimeout(() => {
              uni.hideLoading()
              uni.showToast({
                title: '确认收货成功',
                icon: 'success'
              })
              this.onRefresh()
            }, 800)
          }
        }
      })
    },
    
    // 返回
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.order-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f6fa;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: linear-gradient(135deg, #ff80ab 0%, #ff4081 100%);
    color: #fff;
    
    .title {
      font-size: 18px;
      font-weight: bold;
    }
  }
  
  .status-scroll {
	position: fixed;
	top: 0;
	width: 100%;
	z-index: 999;
    white-space: nowrap;
    padding: 12px 15px;
    background-color: #fff;
    border-bottom: 1px solid #f0f0f0;
    
    .status-item {
      display: inline-block;
      padding: 5px 15px;
      margin-right: 10px;
      border-radius: 15px;
      font-size: 14px;
      color: #666;
      background-color: #f5f5f5;
      
      &.active {
        background: linear-gradient(135deg, #ff80ab 0%, #ff4081 100%);
        color: #fff;
      }
    }
  }
  
  .order-list {
    flex: 1;
    margin-top: 100rpx;
    .order-card {
      background-color: #fff;
      border-radius: 12px;
      margin: 12px;
      padding: 15px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      
      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        padding-bottom: 10px;
        border-bottom: 1px solid #f0f0f0;
        
        .order-no {
          font-size: 13px;
          color: #666;
        }
        
        .order-status {
          font-size: 14px;
          font-weight: bold;
        }
      }
      
      .goods-info {
        display: flex;
        margin-bottom: 15px;
        
        .goods-image {
          width: 80px;
          height: 80px;
          border-radius: 6px;
          margin-right: 12px;
          object-fit: cover;
        }
        
        .goods-detail {
          flex: 1;
          
          .goods-title {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
            font-size: 15px;
            color: #333;
            margin-bottom: 5px;
            line-height: 1.4;
          }
          
          .goods-spec {
            display: block;
            font-size: 12px;
            color: #999;
            margin-bottom: 8px;
          }
          
          .goods-price {
            display: block;
            font-size: 16px;
            color: #ff4d4f;
            font-weight: bold;
          }
        }
      }
      
      .order-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 10px;
        border-top: 1px solid #f0f0f0;
        margin-bottom: 15px;
        
        .order-time {
          font-size: 12px;
          color: #999;
        }
        
        .order-amount {
          font-size: 14px;
          color: #333;
          font-weight: bold;
        }
      }
      
      .order-actions {
        display: flex;
        justify-content: flex-end;
        
        .action-btn {
          height: 30px;
          line-height: 30px;
          padding: 0 12px;
          font-size: 13px;
          border-radius: 15px;
          margin-left: 10px;
          border: 1px solid #d9d9d9;
          background-color: #fff;
          
          &::after {
            border: none;
          }
        }
        
        .cancel-btn {
          color: #666;
          border-color: #d9d9d9;
        }
        
        .pay-btn {
          color: #fff;
          background: linear-gradient(135deg, #ff4d4f, #ff7875);
          border: none;
        }
        
        .confirm-btn {
          color: #fff;
          background: linear-gradient(135deg, #10ac84, #1dd1a1);
          border: none;
        }
        
        .view-btn {
          color: #7e7e7e;
          border-color: #8b8b8b;
        }
      }
    }
    
    .load-more {
      text-align: center;
      padding: 15px;
      color: #999;
      font-size: 14px;
    }
    
    .empty-order {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 60px;
      
      .empty-image {
        width: 200px;
        height: 200px;
        opacity: 0.6;
        margin-bottom: 20px;
      }
      
      .empty-text {
        font-size: 16px;
        color: #999;
      }
    }
  }
}
</style>